// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import SaveManager from "./SaveManager";

export enum AudioEffectType {
    goldDrop,
    hit,
    upgrade
}


const { ccclass, property } = cc._decorator;

@ccclass
export default class AudioManager extends cc.Component {

    @property(cc.AudioClip)
    bgm: cc.AudioClip = null;
    @property(cc.AudioClip)
    goldDrop: cc.AudioClip = null;
    @property(cc.AudioClip)
    hit: cc.AudioClip = null;
    @property(cc.AudioClip)
    upgrade: cc.AudioClip = null;


    private static _single: AudioManager;
    public static get single(): AudioManager {
        return AudioManager._single;
    }

    protected onLoad(): void {
        if (AudioManager._single == null) {
            AudioManager._single = this;
        } else {
            this.node.destroy();
            this.node.removeFromParent();
        }
        cc.game.addPersistRootNode(this.node);
    }




    public playBgm(): void {
        var userdata = SaveManager.single.userdata;
        if (!userdata.isPlayBgm) {
            if (cc.audioEngine.isMusicPlaying) {
                cc.audioEngine.stopMusic();
            }
            return;
        }
        cc.audioEngine.playMusic(this.bgm, true);
    }
    public stopBgm(): void {
        cc.audioEngine.stopMusic();
    }

    public playEffect(audioEffect: AudioEffectType) {
        var userdata = SaveManager.single.userdata;
        if (!userdata.isPlayeAudioEffect) {
            return;
        }
        let clip: cc.AudioClip = null;
        switch (audioEffect) {
            case AudioEffectType.goldDrop:
                clip = this.goldDrop;
                break;
            case AudioEffectType.hit:
                clip = this.hit;
                break;
            case AudioEffectType.upgrade:
                clip = this.upgrade;
                break;
        }
        cc.audioEngine.playEffect(clip, false);
    }
}
